import 'package:account_book/common/dao/history_dao.dart';
import 'package:account_book/pages/bill/index.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:get/get.dart';

class BillController extends GetxController {

  final state = BillState();

  @override
  void onReady() {
    super.onReady();
    _loadData();
  }

  void switchDate (DateTime dateTime) {
    state.currentDate = dateTime;
    _loadData();
  }


  void _loadData () async {
    DateTime now = state.currentDate;
    DateTime startDate = DateTime(now.year, 1, 1);
    DateTime endDate = DateTime(now.year, 12, 31);
    List<Map<String,dynamic>> list = await HistoryDao.instance.countGroupMonthByDate(DateUtil.formatDate(startDate, format: "yyyy-MM-dd"),
        DateUtil.formatDate(endDate, format: "yyyy-MM-dd"));

    state.income = 0.0;
    state.expend = 0.0;
    state.tableData.clear();
    for(Map<String,dynamic> map in list) {
      state.income = NumUtil.add(state.income, map['income']);
      state.expend = NumUtil.add(state.expend, map['expend']);

      state.tableData.add({
        'date': map['date'],
        'income': map['income'],
        'expend': map['expend'],
        'surplus': NumUtil.subtract(map['income'], map['expend'])
      });
    }
    state.surplus = NumUtil.subtract(state.income, state.expend);
  }
}